package cn.lili.event.impl;

import cn.hutool.core.util.RandomUtil;
import cn.lili.event.OrderStatusChangeEvent;
import cn.lili.modules.order.order.client.OrderClient;
import cn.lili.modules.order.order.client.OrderItemClient;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderItem;
import cn.lili.modules.order.order.entity.dto.OrderMessage;
import cn.lili.modules.order.order.entity.enums.OrderComplaintStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderItemAfterSaleStatusEnum;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 虚拟商品
 *
 * @author Bulbasaur
 * @since 2021/5/29 9:17 上午
 */
@Component
@RequiredArgsConstructor
public class VerificationOrderExecute implements OrderStatusChangeEvent {

    private final OrderClient orderClient;
    private final OrderItemClient orderItemClient;

    @Override
    public void orderChange(OrderMessage orderMessage) {
        // 订单状态为待核验，添加订单添加核验码
        if (orderMessage.getNewStatus().equals(OrderStatusEnum.TAKE)) {
            // 获取订单信息
            Order order = orderClient.getBySn(orderMessage.getOrderSn());
            // 获取随机数，判定是否存在
            String code = getCode(order.getStoreId());
            //提货码
            order.setVerificationCode(code);
            // 设置订单验证码
            orderClient.update(order);

            OrderItem orderItem = OrderItem.builder()
                    .orderSn(orderMessage.getOrderSn())
                    .afterSaleStatus(OrderItemAfterSaleStatusEnum.NOT_APPLIED.name())
                    .commentStatus(OrderComplaintStatusEnum.NO_APPLY.name()).build();
            // 修改虚拟订单货物可以进行售后、投诉
            orderItemClient.update(orderItem);
        }
    }

    /**
     * 获取随机数 判断当前店铺下是否使用验证码，如果已使用则重新获取
     *
     * @param storeId 店铺ID
     * @return
     */
    private String getCode(String storeId) {
        // 获取八位验证码
        String code = Long.toString(RandomUtil.randomLong(10000000, 99999999));

        Order order = Order.builder().verificationCode(code).storeId(storeId).build();
        if (orderClient.getOne(order) == null) {
            return code;
        } else {
            return this.getCode(storeId);
        }
    }
}
